<template>
  <div class="module_header">
    <div class="title">您好，欢迎来到 <br />全国青少年无人机大赛</div>

    <img class="logo" src="@/assets/logo_min.png" />
  </div>
  <div class="cont">
    <div class="item">
      <el-select v-model="ruleForm.code" class="select">
        <el-option value="" label="+86"></el-option>
        <el-option value="852" label="+852"></el-option>
        <el-option value="853" label="+853"></el-option>
      </el-select>
      <div class="line"></div>
      <input v-model.trim="ruleForm.name" placeholder="请输入手机号" />
    </div>
    <div class="item-hint item-hint-o">
      <img class="img" src="@/assets/common/hint_shen_red.png" />你输入数据有错
    </div>
    <!--item_error错误样式-->
    <div class="item">
      <input v-model.trim="ruleForm.pwd" placeholder="请输入验证码" />
      <span class="code" @click="sendCode">{{btns.sendmsg}}</span>
    </div>
    <!-- <div class="item-hint" v-if="false">
      <img class="img" src="@/assets/common/hint_shen_red.png" />你输入数据有错
    </div> -->
    <div class="btn" @click="() => {
      login();
    }" :disabled="btnDisabled">立即登录</div>

    <div style="display: flex; justify-content: space-between;">
      <div class="text" @click="router.push('/wap/certificate')">证书查询</div>
      <div class="text" @click="router.push('/auth/register')">没有账号,立即注册</div>
    </div>


    <div class="agreement">
      <el-checkbox v-model="ruleForm.checked2" />点击同意并接受即表示您已阅读了解并同意
      <el-button @click="handleaGreement" type="text">《隐私协议》</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive,onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, FormInstance } from "element-plus";
import baseService from "@/service/baseService";
import { setCache } from "@/utils/cache";
let router = useRouter();

// 检测是否是移动设备
const isMobileDevice = () => {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
};

// 在组件挂载时检查设备类型
onMounted(() => {
  if (!isMobileDevice()) {
    // 如果不是移动设备，跳转到PC端登录页面
    router.replace('/'); // 替换为你的PC端登录路由
  }
});



const ruleForm = reactive({
  code: "",
  name: "",
  pwd: "",
  checked2: true,
});

const handleaGreement = () => {
  router.push("/auth/agreement");
};
const handleSuccess = () => {
  router.push("/auth/match/sign_list");
};


const btns = reactive({
  sendmsg: "发送验证码",
  disabled: false
});

const dialogShow = ref(false);

const btnDisabled = ref(false);

/**
 * 登录
 */
const login = () => {
  btnDisabled.value = true;
  if (!ruleForm.checked2) {
    ElMessage.error("您未同意用户协议，请先同意！");
    return;
  }
  // 校验手机号格式
  if (!checkPhone()) {
    return;
  }
  //校验验证码不能为空
  if (ruleForm.pwd === "") {
    ElMessage.error("验证码不能为空！");
    return false;
  }

  baseService
    .post(
      "/front/spuser/login",
      {
        account: ruleForm.code + ruleForm.name,
        verificationCode: ruleForm.pwd,
        loginType: 'wap'
      }
    ).then((res) => {
      if (res.code === 0) {
        const certificate = {
          realName: res.data.realName,
          idCard: res.data.idCard
        };
        setCache("certificate", certificate, true);
        setCache("CacheToken", res.data, true);
        // 成功登录后将token存入cookie
        // 设置cookies
        //$cookies.set("loginCookie", res.data.account, '1m', '/', 'fii-cc.com');
        router.push(res.data.url);
        // 跳转代表队
        //router.push("/team/index");
        // 跳转到领队注册页面
        //router.push("/account/team");
      } else {
        ElMessage.error(res.msg);
      }
      btnDisabled.value = false;
    }
    );
};

// 校验手机号格式
const checkPhone = () => {
  //校验手机号不能为空
  if (ruleForm.name === "") {
    ElMessage.error("手机号格式不正确！");
    return false;
  }
  // 判断国际区号
  if (ruleForm.code === '') {
    if (ruleForm.name.length != 11) {
      ElMessage.error("手机号格式不正确！");
      return false;
    }
  } else if (ruleForm.code === '852') {
    if (!(ruleForm.name.length == 8 || ruleForm.name.length == 9)) {
      ElMessage.error("手机号格式不正确！");
      return false;
    }
  } else if (ruleForm.code === '853') {
    if (ruleForm.name.length != 8) {
      ElMessage.error("手机号格式不正确！");
      return false;
    }
  }
  return true;
};


/**
 * 发送验证码
 */
const sendCode = () => {
  //校验ruleForm.name不能为空
  if (ruleForm.name === "") {
    ElMessage.error("手机号不能为空！");
    return;
  }
  // 校验手机号格式
  if (!checkPhone()) {
    return;
  }

  if (btns.disabled) {
    return;
  }


  //查代表队
  baseService.post("/front/spuser/queryTeamByPhone", {
        phone: ruleForm.code + ruleForm.name
      })
      .then((res) => {
        // 负责人有代表队
        if (res.code === 0 && res.data) {
          btns.sendmsg = "验证码已发送";
          baseService.post("/front/spuser/getCheckCode", {phone: ruleForm.code + ruleForm.name, code: ruleForm.code})
              .then((res) => {
                if (res.code === 0) {
                  ElMessage.success('验证码发送成功');
                  countDown();
                }
              });
        }else{
          // 没有代表队，查询是否是主领队 （1主领队   2副领队）
          baseService.post("/front/spuser/queryTeamUserByPhone", {
            phone: ruleForm.code + ruleForm.name
          }).then((resTeamUser) => {
            debugger
            if (resTeamUser.data && resTeamUser.data.type == 1) {
              btns.sendmsg = "验证码已发送";
              baseService.post("/front/spuser/getCheckCode", {phone: ruleForm.code + ruleForm.name, code: ruleForm.code})
                  .then((res) => {
                    if (res.code === 0) {
                      ElMessage.success('验证码发送成功');
                      countDown();
                    }
                  });
            }else{
              ElMessage.error('手机端请使用代表队账号登录');
            }
          });
        }
      });
}

/**
 * 短信验证码倒计时功能
 */
let timer: any = null;
const countDown = () => {
  let count = 60;
  btns.disabled = true;
  btns.sendmsg = count + "s后重新发送";
  timer = setInterval(() => {
    count--;
    btns.sendmsg = count + "s后重新发送";
    if (count <= 0) {
      clearInterval(timer);
      btns.sendmsg = "发送验证码";
      btns.disabled = false;
    }
  }, 1000);
};
</script>

<style lang="scss" scoped>
@import "./style.scss";
</style>
